package com.tuda.common.pay.wx.api;

import com.google.gson.Gson;
import com.tuda.common.pay.common.bean.PayOrder;
import com.wechat.pay.java.core.auth.WechatPay2Credential;
import com.wechat.pay.java.core.cipher.SignatureResult;
import com.wechat.pay.java.core.cipher.Signer;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.core.env.Environment;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import okhttp3.HttpUrl;
import java.security.Signature;
import java.util.Base64;

/**
 * @author Ys
 * @date 2021年07月26日 14:33
 */
public class WxPcPay {


    @Resource
    private Environment environment;


    /**
     *
     * @throws Exception
     */
    public void createWxOrder(PayOrder payOrder) throws Exception{
        HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/native");
        Map<String, Object> parameters = new TreeMap<String, Object>();
        parameters.put("mchid", "1649419050");
        parameters.put("appid", "wx0076a737136b24d3");
        parameters.put("out_trade_no", "50120140703");
        parameters.put("description", "途达运输");
        parameters.put("notify_url", "https://tuda.chn-yulink.com/applet/order/wxMiniNotify");
        Map<String, Object> amount = new HashMap<>();
        amount.put("total", 1);
        amount.put("currency", "CNY");
        parameters.put("amount", amount);
        StringEntity entity = new StringEntity(new Gson().toJson(parameters));
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //完成签名并执行请求
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            int statusCode = response.getStatusLine().getStatusCode();
            //处理成功
            if (statusCode == 200) {
                System.out.println("success,return body = " + EntityUtils.toString(response.getEntity()));
                //处理成功，无返回Body
            } else if (statusCode == 204) {
                System.out.println("success");
            } else {
                System.out.println("failed,resp code = " + statusCode+ ",return body = " + EntityUtils.toString(response.getEntity()));
                throw new IOException("request failed");
            }
            httpClient.close();
        } finally {
            response.close();
        }
    }


    public static void main(String[] args) throws Exception {
        WxPcPay pcPay = new WxPcPay();
        pcPay.createWxOrder(null);
    }
}
